import React from 'react'
import { Button, message, Modal} from 'antd'
import Table from '../../../components/Table'
import 'whatwg-fetch'
import API from '../../../axios/api'
import { UserType, } from '../../../utils/system-data'
import { dateToString } from '../../../utils/utils'
import SearchBar from "../../../components/SearchBar";
import {FormModal} from "../../../components/ModalForm";
import SalesDetailList from "./DetailList";
import moment from 'moment';
import {withRouter,Redirect, Link} from "react-router-dom";
import {inject, observer} from "mobx-react";
require('es6-promise').polyfill();


const columns = [
    { dataIndex: '', title: '序号', width: 80,render: (text, record,index) =>  <span>{index + 1}</span>},
    { dataIndex: 'HallName', title: '班级名称', width: 240,},
    { dataIndex: 'RudderName', title: '所属分舵', width: 240,},
    { dataIndex: 'HallUserCount', title: '班级经营者数量', width: 200,},
    { dataIndex: 'OrderMonthAmount', title: '销售总额', width: 200,},
    { dataIndex: 'GroupBuyingCount', title: '发起活动次数', width: 200,},

]
@withRouter @inject('appStore') @observer
class SalesStatistics extends React.Component {
    constructor(props) {
        super(props)
        const {user, rudder, rudderList} = props.appStore
        const monthTime =  dateToString(new Date())

        this.state = {
            user: user,
            rudder: rudder,
            rudderList: rudderList,
            tData: [],
            item: {},
            loading: true,
            modalShowDetail: false,
            modalShowExport: false,
            initHallList: [],
            godetail:false,
            RudderId:user.RudderId,
            HallId:'',
            monthTime:monthTime,
            Page: 1,
            Pages:1,
        }
    }

    componentWillReceiveProps(nextProps){
        const monthTime =  dateToString(new Date())
        const {user, rudder, rudderList} = this.props.appStore
         this.setState({
             user: user,
             rudder: rudder,
             rudderList: rudderList,
             RudderId:user.RudderId,
             monthTime:monthTime
         })
     }
    
    onPageChange = (e) =>{
        if(this.props.appStore.salesdata.RudderId && this.props.appStore.salesdata.monthTime){
            this.props.appStore.initsalesdata({
                RudderId:this.props.appStore.salesdata.RudderId,
                monthTime:this.props.appStore.salesdata.monthTime
            })
        }

        this.props.appStore.initsalespage(e)
        this.setState({
            Page:e,
        },()=>{
           
            this.fetchTableData()
        })
    }


    // 获取表格数据
    fetchTableData =  async () => {
        let parms = {}
        if(this.props.appStore.salesdata.RudderId && this.props.appStore.salesdata.monthTime){
            parms = {
                Page:this.props.appStore.salespage ? this.props.appStore.salespage :this.state.Page,
                PageSize: 10,
                monthTime:this.props.appStore.salesdata.monthTime,
                RudderId:this.props.appStore.salesdata.RudderId,
                HallId:this.state.HallId,
            }
        }else{
            parms = {
                Page:this.props.appStore.salespage ? this.props.appStore.salespage :this.state.Page,
                PageSize: 10,
                monthTime: this.state.monthTime,
                RudderId:this.state.RudderId,
                HallId:this.state.HallId,
            }
        }
       // await API.getRudderMonth(parms).then((res) => {
        await API.fetchHallSallPages(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List,
                    Pages:res.Data.Pages
                });
            }
            this.setState({
                loading: false
            });
        })
    }


    // 初始化班级
    initHallList =  async (rudderId) => {
        let _initHallList = []
        let params = {
            ...API.config,
            RudderId: this.state.RudderId
        }
        await API.fetchHallPages(params).then((res) => {
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initHallList.push({value: item.Id, mean: item.HallName}))
                this.setState({
                    initHallList: _initHallList,
                })
            }
        })
    }
    onCancel = () =>{
        this.setState({
            modalShowDetail: false
        })
    }
    componentWillMount() {
        this.initHallList()
    }

    componentDidMount() {
        this.fetchTableData()
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'detail') {
            let data = {
                monthTime: this.state.monthTime,
                RudderId:item.RudderId,
            }
           this.props.appStore.initsalesdata(data)
           this.props.appStore.initsalespage(this.props.appStore.salespage)

           this.setState({
            godetail:true,
            HallId:item.Id,
            RudderId:item.RudderId
           })
        }
    }

    onSearch = (searchFields) => {
        this.props.appStore.initsalesdata({})
        this.props.appStore.initsalespage(1)
        if(!searchFields.RudderId && this.state.RudderId == '-'){
            message.error('请选择分舵！')
            return false;
        }

        const _monthTime = (searchFields && searchFields.start)? dateToString(new Date(searchFields.start)): dateToString(new Date())
        this.setState({
            HallId:searchFields && searchFields ? searchFields.HallId : '',
            RudderId: searchFields && searchFields.RudderId ?  searchFields.RudderId : this.state.RudderId,
            monthTime:_monthTime,
            Page:1
        },()=>{
            this.fetchTableData()
        })
    }
    searchRudderChange = (v)=>{
        this.setState({
            searchHallId : "-1"
        })
        this.initHallList(v)
    }
    searchFields = () => {
        let _fields =[
        //     {
        //     title: '班级名称',
        //     key: 'HallId',
        //     type: 'select',
        //     items: () => this.state.initHallList,
        // },
        {
            title: '时间',
            key: 'start',
            type: 'monthPicker',
            defaultValue: moment(new Date(), 'YYYY-MM')
        }]
        if(this.state.user && this.state.user.UserRankType === UserType.ADMIN || this.state.user.RudderId == "-"){
            _fields = [{
                title: '分舵名称',
                key: 'RudderId',
                type: 'select',
                // defaultValue: this.state.rudder.mean,
                items: () => this.state.rudderList,
                onChange: this.searchRudderChange,
            }, ].concat(_fields)
        }
        return _fields
    }

    showExport = (searchFields) =>{
        const _monthTime = (searchFields && searchFields.start)? dateToString(new Date(searchFields.start)): dateToString(new Date())
        let parms = {
            RudderId:  (searchFields && searchFields.RudderId) || this.state.rudder.value, // 海西分舵 dfhshsdfhdf56735734
            MonthTime: _monthTime,
            DataEmailAddress: '',
        }
        this.setState({
            params: parms,
            modalShowExport: true
        })
    }

    onCancelExport = () => {
        this.setState({
            modalShowExport: false
        })
    }
    exportFields = () => {
        return [{
            label: '邮箱',
            type: 'input',
            name: 'email',
            options: {
                rules: [{
                    required: true,
                    message: '必填!',
                }]
            }
        },]
    }

    onExport = (val) =>{
        let parms = this.state.params
        parms.DataEmailAddress = val.email
        API.getRudderMonthDataExcel(parms).then((res) => {
            if(res.Code === 200) {
                message.success('导出成功')
                this.onCancelExport()
            }else{
                message.error(res.Message)
            }
        })
    }

    render() {
       if(this.state.godetail){
         let path = "/statistics/salesdetail"
        this.props.history.push({ pathname : path ,state : {
                monthTime:this.state.monthTime,
                RudderId:this.state.RudderId,
                HallId:this.state.HallId
        } })
        }
        return (
            <div id="wrap">
                <SearchBar
                    onSubmit={this.onSearch}
                    fields={this.searchFields()}
                />
                <div style={{ paddingTop: 10 }}>
                    <Button onClick={this.showExport} >导出</Button>
                </div>
                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns}
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [
                                { key: 'detail', name: '详情', color: 'blue', icon: 'ordered-list'},
                            ]}
                            scroll={{y: 385 }}
                            total={this.state.Pages}
                            onChange={this.onPageChange}
                            currentPage={this.props.appStore.salespage}
                        />
                    </div>
                    <SalesDetailList
                        modalKey="add"
                        visible={this.state.modalShowDetail}
                        title="详情"
                        onOk={this.onOk}
                        onCancel={this.onCancel}
                        userId={this.state.item.UserId}
                        monthTime={this.state.monthTime}
                        width="70%"
                    />
                    <FormModal
                        modalKey="export"
                        visible={this.state.modalShowExport}
                        title="导出"
                        fields={this.exportFields()}
                        onOk={this.onExport}
                        onCancel={this.onCancelExport}
                        okText="保存"
                    />
                </div>
            </div>
        )
    }
}
export default SalesStatistics
